package org.geektimes.injection.initializer;


import org.geektimes.injection.comparator.OrderComparator;

import javax.servlet.*;
import javax.servlet.annotation.HandlesTypes;
import java.lang.reflect.Modifier;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

@HandlesTypes(WebApplicationContextInitializer.class)
public class ServletInjectionInitializer implements ServletContainerInitializer, ServletContextListener {

    private final List<WebApplicationContextInitializer> initializers = new LinkedList<>();

    @Override
    public void onStartup(Set<Class<?>> webInitializerClasses, ServletContext servletContext) throws ServletException {
        servletContext.addListener(this);
        if (webInitializerClasses != null) {
            for (Class<?> waiClass : webInitializerClasses) {
                if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&
                        WebApplicationContextInitializer.class.isAssignableFrom(waiClass)) {
                    try {
                        initializers.add((WebApplicationContextInitializer) waiClass.newInstance());
                    } catch (Throwable ex) {
                        throw new ServletException("Failed to instantiate WebApplicationContextInitializer class", ex);
                    }
                }
            }
        }

        if (initializers.isEmpty()) {
            servletContext.log("No WebApplicationContextInitializer types detected on classpath");
            return;
        }
        initializers.sort(new OrderComparator());
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        for (WebApplicationContextInitializer initializer : initializers) {
            initializer.contextInitialized(sce.getServletContext());
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        for (int i = initializers.size() - 1; i >= 0; i--) {
            initializers.get(i).contextDestroyed(sce.getServletContext());
        }
    }
}
